package cn.com.dhcc.turbo.web.controller.registry;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.modulehandler.valuebean.LikeValue;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu.LEAF_MENU;
import cn.com.dhcc.app.pub.core.consts.NodeInfoParam;
import cn.com.dhcc.turbo.entity.registry.DomainInfo;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.registry.SynchronizeInfo.SyncType;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo;
import cn.com.dhcc.turbo.service.registry.DomainInfoService;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;
import cn.com.dhcc.turbo.service.registry.sync.ISynchronizeToGapService;

/**
 * 业务域管理controller
 * 
 * @日期：2014-5-15 下午4:13:27
 * @作者：张洪涛
 * @版权所有：东华软件
 * @版本：1.0
 */
@Controller
@RequestMapping("/registry")
@TurboMenu(belongToMenu=LEAF_MENU.DOMAIN_MGR)
public class DomainInfoController extends BaseController {
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.SAI);
	@Autowired
	private DomainInfoService doMainService;
	@Autowired
	private NodeInfoService nodeService;
	@Autowired
	private ISynchronizeToGapService synchronizeToGapService;

	/**
	 * 获取业务域业务域
	 * 
	 * @param model
	 * @param pager
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/domain_info_list")
	public String list(Model model,HttpSession httpSession, Pager pager, String searchName) {
		WhereCondition condition = new WhereCondition();
		condition.where().eq("t1.status", "1");
		if (!"".equals(searchName) && searchName != null) {
			condition.and().like("t1.name", LikeValue.roundLike(searchName));
		}
		condition.orderBy("t1.mtime desc");
		
		try {
			PagerData<DomainInfo> pagerData = doMainService.list(pager,
					condition);
			model.addAttribute(DATA_KEY, pagerData.getDatas());
			setTotoal(model, pagerData.getTotal());
			NodeInfo nodeInfo = nodeService.getLocalNode();
			UserInfo user = (UserInfo)getCurrentUserInfo(httpSession);
			if(user != null){
				model.addAttribute("nodeAdmin", user.getUserType());
			}
			model.addAttribute("nodeInfo", nodeInfo);
			model.addAttribute("netType", NodeInfoParam.isInnerNode());
		} catch (Exception e) {
			logger.error("获取业务域信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/domain_info_list";
	}
	/**
	 * 业务域注册
	 * @param model
	 * @param nodeId
	 * @return
	 */
	@RequestMapping(value = "/domain_info_add")
	public String domainAdd(Model model,String nodeId) throws DaoException {
		try {
			String code = doMainService.MaxCode();
			if("".equals(code) || code == null){
				code = "01";
			}else{
				code = String.format("%02d", Integer.parseInt(code)+1);
			}
			model.addAttribute("code", code);
		} catch (Exception e) {
			logger.error("注册业务域信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/domain_info_add";
	}
	/**
	 * 
	 * @param model
	 * @param vo
	 * @return
	 */
	@RequestMapping(value = "/add_domain_info", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addDomain(Model model, DomainInfo vo) {
		try {
			vo.setId(UUIDGenerator.getUUID());
			vo.setMtime(new Date());
			doMainService.addAndSync(vo);
			return jsonSuccessResult("注册成功");
		} catch (Exception e) {
			logger.error("注册业务域信息失败", e);
			return jsonFailResult("注册业务域信息失败");
		}
	}
	/**
	 * 获取业务域信
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/domain_info_get", method = RequestMethod.GET)
	public String get(Model model,String id) {
		try {
			DomainInfo vo = doMainService.get(id);
			model.addAttribute(DATA_KEY, vo);
		} catch (Exception e) {
			logger.error("获取业务域信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/domain_info_get";
	}
	@RequestMapping(value = "/domain_info_update/{id}", method = RequestMethod.GET)
	public String domainUpdate(@PathVariable String id, Model model) {
		try {
			DomainInfo vo = doMainService.get(id);
			model.addAttribute(DATA_KEY, vo);
		} catch (Exception e) {
			logger.error("注册业务域信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/domain_info_update";
	}
	/**
	 * 修改业务域
	 * @param model
	 * @param vo
	 * @param newNodeName
	 * @return
	 */
	@RequestMapping(value = "/update_domain_info", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> updateDomain(Model model, DomainInfo vo) {
		try {
			vo.setMtime(new Date());
			doMainService.updateAndSyncDomain(vo);
			return jsonSuccessResult("修改业务域成功");
		} catch (Exception e) {
			logger.error(" 修改业务域信息失败", e);
			return jsonFailResult("修改业务域信息失败");
		}
	}
	/**
	 * 删除
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/domain_info_delete", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> delete(Model model, String id) {
		String msg = "";
		try {
			//List<SysInfo> list = sysInfoService.listByDomainId(id);
			/*if(list.size() > 0 ){
				msg = "删除失败,业务域已关联业务系统!";
				return jsonFailResult(msg);
			}else{*/
				DomainInfo vo = doMainService.get(id);
				vo.setStatus("0");
				doMainService.updateAndSyncDomain(vo);
				msg = "删除成功";
				return jsonSuccessResult(msg);
			//}
		} catch (Exception e) {
			msg = "删除失败";
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
	
	/**
	 * 验证业务域名称唯一性
	 * 
	 * @param newValue
	 * @param oldValue
	 * @return
	 */
	@RequestMapping("/is_domain_name_unique")
	@ResponseBody
	public String isDomainNameUnique(
			@RequestParam("name") String newValue,
			@RequestParam("oldValue") String oldValue) {
		try {
//			NodeInfo node = nodeService.getLocalNode();
			if (doMainService.isPropertyUnique("name", newValue.trim(),oldValue.trim())) {
				return FORM_CHECK_SUCCESS;
			} else {
				return FORM_CHECK_FAIL;
			}
		} catch (Exception e) {
			return FORM_CHECK_FAIL;
		}
	}
	
	/**
	 * 根据Id启用适配器
	 * 
	 * @param id
	 * @param model
	 * @return
	 */

	@RequestMapping(value = "/domain_info_sync")
	@ResponseBody
	public Map<String, Object> sync() {
		try {
			List<DomainInfo> list=doMainService.list(new WhereCondition());
			synchronizeToGapService.sendToGap(list, SyncType.DOMAIN_INFO, 
					NodeInfoParam.GAP_PARAM.IP, NodeInfoParam.GAP_PARAM.Port, 
					NodeInfoParam.GAP_PARAM.Home, NodeInfoParam.GAP_PARAM.UserName,
					NodeInfoParam.GAP_PARAM.Password);
			return jsonSuccessResult("业务域同步到网闸成功");
		} catch (Exception e) {
			return jsonFailResult("业务域同步到网闸失败,请稍后再试"+e);
		}
	}
}
